//
//  DMCommercialManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/8/20.
//

#import "DMCommercialManager.h"
#import <AdjustSdk/AdjustSdk.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FirebaseCore/FirebaseCore.h>
#import "DMConfigReader.h"
#import "IMLogUtils.h"
#import "DMAdjustManager.h"
#import "../../API/AdStrategy/IMAdStrategyManager.h"
#import "../../API/AdStrategy/IMSDKStartupConfigManager.h"

// 统计数据存储Key
#define KEY_FB_SHOW_COUNT_TODAY @"fb_show_count_today"
#define KEY_FB_CLICK_COUNT_TODAY @"fb_click_count_today"
#define KEY_LAST_STAT_DATE @"last_stat_date"

// BMS配置Key
#define KEY_SDK_FB_CTL @"sdk_fb_ctl"
#define KEY_SDK_FB_LV_EVENT @"sdk_fb_lv_event"
#define KEY_SDK_ADJUST_EVENT @"sdk_adjust_event"

@interface DMCommercialManager()

// BMS配置参数
@property (nonatomic, strong) NSString *fbControlConfig;        // sdk_fb_ctl
@property (nonatomic, strong) NSString *fbLevelEventConfig;     // sdk_fb_lv_event
@property (nonatomic, strong) NSString *adjustEventConfig;      // sdk_adjust_event

// FB控制参数现在从本地配置解析获取

// 解析后的配置
@property (nonatomic, strong) NSDictionary *fbLevelEventDict;   // FB关卡事件配置
@property (nonatomic, strong) NSDictionary *adjustEventDict;    // Adjust事件配置

// 广告位配置
@property (nonatomic, strong) NSDictionary *adUnitConfigs;      // 广告位配置

// 广告网络信息存储
@property (nonatomic, strong) NSMutableDictionary *adNetworkInfoDict;  // 存储广告位ID和网络信息的映射

@end

@implementation DMCommercialManager

+ (instancetype)sharedInstance {
    static DMCommercialManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DMCommercialManager alloc] init];
    });
    return instance;
}


#pragma mark - 双广告位配置方法

+ (BOOL)isDualAdEnabledForAdType:(NSString *)adType {
    if ([DMConfigReader isDualAdConfigEnabled]){
        return YES;
    }
    return NO;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initializeDefaultConfigs];
        [self checkAndResetDailyStats];
    }
    return self;
}


#pragma mark - 初始化配置

- (void)initializeDefaultConfigs {
    // 设置默认的FB控制参数
    self.fbControlConfig = @"0;2;100";
    
    // 初始化配置字典
    self.fbLevelEventDict = @{};
    self.adjustEventDict = @{};
    self.adUnitConfigs = @{};
    
    // 初始化FB广告统计数据
    self.fbAdStatistics = [[NSMutableDictionary alloc] init];
    
    // 初始化广告网络信息存储字典
    self.adNetworkInfoDict = [[NSMutableDictionary alloc] init];
    
    // 从广告策略接口的SDK启动配置中获取配置并更新
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 开始从广告策略接口获取SDK启动配置"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
        if (strategyManager) {
            // 获取SDK启动配置
            IMSDKStartupConfig *sdkConfig = [strategyManager getSDKStartupConfig];
            if (sdkConfig) {
                [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] SDK启动配置获取成功，开始转换配置数据"];
                
                // 构建配置字典，将SDK启动配置转换为BMS配置格式
                NSMutableDictionary *configDict = [NSMutableDictionary dictionary];
                
                // 提取Facebook控制配置
                if (sdkConfig.sdk_config_fb_ctl && [sdkConfig.sdk_config_fb_ctl isKindOfClass:[NSString class]]) {
                    configDict[KEY_SDK_FB_CTL] = sdkConfig.sdk_config_fb_ctl;
                }
                
                // 提取Adjust事件配置
                if (sdkConfig.sdk_config_adjust_event && [sdkConfig.sdk_config_adjust_event isKindOfClass:[NSString class]]) {
                    configDict[KEY_SDK_ADJUST_EVENT] = sdkConfig.sdk_config_adjust_event;
                }
                
                // 提取Facebook关卡事件配置
                if (sdkConfig.sdk_config_fb_level_event && [sdkConfig.sdk_config_fb_level_event isKindOfClass:[NSString class]]) {
                    configDict[KEY_SDK_FB_LV_EVENT] = sdkConfig.sdk_config_fb_level_event;
                }
                
                if (configDict.count > 0) {
                    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 配置数据转换成功，调用updateBMSConfig更新"];
                    
                    // 在主线程调用updateBMSConfig
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self updateBMSConfig:configDict];
                        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] SDK启动配置初始化完成"];
                    });
                } else {
                    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 未找到有效的配置数据"];
                }
            } else {
                [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] SDK启动配置获取失败或配置为空"];
            }
        } else {
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] IMAdStrategyManager实例获取失败"];
        }
    });
}

#pragma mark - 关卡胜利上报接口

- (void)setLevelWin:(NSInteger)levelId {
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] setLevelWin called with levelId: %ld", (long)levelId];
    
    // 参数验证
    if (levelId <= 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Invalid levelId: %ld", (long)levelId];
        return;
    }
    
    // 3. Facebook关卡价值事件上报（BMS参数控制）
    [self trackFacebookLevelWinIfConfigured:levelId];
    
    // 4. Adjust事件上报（BMS参数控制）
    [self trackAdjustLevelWinIfConfigured:levelId];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] setLevelWin completed for levelId: %ld", (long)levelId];
}

- (void)setLevelWinWithString:(NSString *)levelId {
    if (!levelId || levelId.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Invalid levelId string: %@", levelId];
        return;
    }
    
    NSInteger levelIdInt = [levelId integerValue];
    [self setLevelWin:levelIdInt];
}

#pragma mark - Firebase事件上报

- (void)trackFirebaseLevelWin:(NSInteger)levelId {
    // 根据关卡ID选择对应的事件名称（001-010循环）
    NSInteger eventIndex = ((levelId - 1) % 10) + 1;
    NSString *eventName = [NSString stringWithFormat:@"Total_Ads_Revenue_%03ld", (long)eventIndex];
    
    // 构造事件参数
    NSDictionary *parameters = @{
        @"level_id": @(levelId),
        @"timestamp": @([[NSDate date] timeIntervalSince1970]),
        @"user_id": [self getCurrentUserId] ?: @"",
        @"session_id": [self getCurrentSessionId] ?: @""
    };
    
    // 使用WDFirebaseManager进行事件上报
    
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Firebase事件上报: %@ - Level: %ld", eventName, (long)levelId];
}

#pragma mark - Facebook事件上报

- (void)trackFacebookLevelEvent:(NSString *)levelId value:(double)value {
    NSString *eventName = [NSString stringWithFormat:@"fb_level_win_%@", levelId];
    
    // 构造事件参数
    NSDictionary *parameters = @{
        @"level_id": levelId,
        @"level_value": @(value)
    };
    
    // 调用Facebook事件上报
    [[FBSDKAppEvents shared]logEvent:levelId parameters:parameters];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Facebook关卡事件上报: %@ with value: %.2f", eventName, value];
}

- (void)trackFacebookLevelWinIfConfigured:(NSInteger)levelId {
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 开始检查Facebook关卡事件上报 - 关卡ID: %ld", (long)levelId];
    
    if (!self.fbLevelEventConfig || self.fbLevelEventConfig.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB关卡事件配置为空，跳过上报"];
        return;
    }
    
    NSString *levelIdStr = @(levelId).stringValue;
    NSString *eventKey = [NSString stringWithFormat:@"fb_level_win_%@", levelIdStr];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 检查FB事件匹配 - 事件键: %@", eventKey];
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 当前FB事件配置: %@", self.fbLevelEventDict];
    
    NSNumber *valueNumber = self.fbLevelEventDict[eventKey];
    if (valueNumber) {
        double value = valueNumber.doubleValue;
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] ✅ 匹配到FB事件配置，开始上报 - 事件: %@, 价值: %.2f", eventKey, value];
        [self trackFacebookLevelEvent:levelIdStr value:value];
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] ❌ 未匹配到FB事件配置，跳过上报 - 关卡ID: %ld 不在配置列表中", (long)levelId];
    }
}

#pragma mark - Adjust事件上报

- (void)trackAdjustEvent:(NSString *)eventToken eventName:(NSString *)eventName {
    // Adjust事件上报逻辑
    if (!eventToken || eventToken.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Adjust event token is empty for event: %@", eventName];
        return;
    }
    
    // 调用Adjust事件上报
     
    ADJEvent *event = [[ADJEvent alloc]initWithEventToken:eventToken];
    [Adjust trackEvent:event];
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Adjust事件上报: %@ with token: %@", eventName, eventToken];
}

- (void)trackAdjustLevelEvent:(NSInteger)level {
    // 根据关卡获取对应的Adjust事件Token
    NSString *eventToken = [self getAdjustEventTokenForLevel:level];
    if (eventToken && eventToken.length > 0) {
        [self trackAdjustEvent:eventToken eventName:[NSString stringWithFormat:@"Level_%ld", (long)level]];
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] No Adjust event token found for level: %ld", (long)level];
    }
}

- (void)trackAdjustPurchaseEvent:(NSString *)productId revenue:(CGFloat)revenue currency:(NSString *)currency {
    // 根据商品ID获取对应的Adjust购买事件Token
    NSString *eventToken = [self getAdjustPurchaseEventTokenForProduct:productId];
    if (eventToken && eventToken.length > 0) {
        // 创建带收入信息的Adjust事件
        if ([DMAdjustManager respondsToSelector:@selector(sharedManager)]) {
            id adjustManager = [DMAdjustManager performSelector:@selector(sharedManager)];
            if ([adjustManager respondsToSelector:@selector(adjustCustomEventWithCustomId:)]) {
                // 构建事件参数
                NSDictionary *eventParams = @{
                    @"event_token": eventToken,
                    @"revenue": @(revenue),
                    @"currency": currency ?: @"USD",
                    @"product_id": productId ?: @"",
                    @"timestamp": @([[NSDate date] timeIntervalSince1970])
                };
                
                [adjustManager performSelector:@selector(adjustCustomEventWithCustomId:) withObject:eventParams];
            }
        }
        
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Adjust购买事件上报: %@ - Product: %@, Revenue: %.2f %@", eventToken, productId, revenue, currency];
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] No Adjust purchase event token found for product: %@", productId];
    }
}

- (void)trackAdjustLevelWinIfConfigured:(NSInteger)levelId {
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 开始检查Adjust关卡事件上报 - 关卡ID: %ld", (long)levelId];
    
    if (!self.adjustEventConfig || self.adjustEventConfig.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Adjust事件配置为空，跳过上报"];
        return;
    }
    
    NSString *levelIdStr = @(levelId).stringValue;
    NSString *eventKey = [NSString stringWithFormat:@"level_win_%@", levelIdStr];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 检查Adjust事件匹配 - 事件键: %@", eventKey];
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 当前Adjust事件配置: %@", self.adjustEventDict];
    
    NSString *eventToken = self.adjustEventDict[eventKey];
    if (eventToken && eventToken.length > 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] ✅ 匹配到Adjust事件配置，开始上报 - 事件: %@, Token: %@", eventKey, eventToken];
        [self trackAdjustEvent:eventToken eventName:eventKey];
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] ❌ 未匹配到Adjust事件配置，跳过上报 - 关卡ID: %ld 不在配置列表中", (long)levelId];
    }
}

#pragma mark - BMS配置管理

- (void)updateBMSConfig:(NSDictionary *)config {
    if (!config || ![config isKindOfClass:[NSDictionary class]]) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Invalid BMS config: %@", config];
        return;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Updating BMS config: %@", config];
    
    // 更新FB控制参数
    NSString *fbCtl = config[KEY_SDK_FB_CTL];
    if (fbCtl && [fbCtl isKindOfClass:[NSString class]]) {
        self.fbControlConfig = fbCtl;
        // FB控制参数现在从本地配置解析获取
    }
    
    // 更新FB关卡事件配置
    NSString *fbLvEvent = config[KEY_SDK_FB_LV_EVENT];
    if (fbLvEvent && [fbLvEvent isKindOfClass:[NSString class]]) {
        self.fbLevelEventConfig = fbLvEvent;
        [self parseFBLevelEventConfig:fbLvEvent];
    }
    
    // 更新Adjust事件配置
    NSString *adjustEvent = config[KEY_SDK_ADJUST_EVENT];
    if (adjustEvent && [adjustEvent isKindOfClass:[NSString class]]) {
        self.adjustEventConfig = adjustEvent;
        [self parseAdjustEventConfig:adjustEvent];
    }
}

- (void)parseFBControlConfig:(NSString *)configString {
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 开始解析FB控制配置: %@", configString ?: @"(空)"];
    
    if (!configString || configString.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB控制配置为空，保持当前配置"];
        return;
    }
    
    NSArray *params = [configString componentsSeparatedByString:@";"];
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 分割得到%lu个参数: %@", (unsigned long)params.count, params];
    
    if (params.count == 3) {
        NSInteger fbSwitchFlag = [params[0] integerValue];
        NSInteger fbShowThreshold = [params[1] integerValue];
        NSInteger fbClickRateThreshold = [params[2] integerValue];
        
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB控制配置解析成功 - 切源开关:%ld, 展示阈值:%ld, 点击率阈值:%ld",
              (long)fbSwitchFlag, (long)fbShowThreshold, (long)fbClickRateThreshold];
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB控制配置格式错误，期望3个参数，实际%lu个", (unsigned long)params.count];
    }
}

- (void)parseFBLevelEventConfig:(NSString *)configString {
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 开始解析FB等级事件配置: %@", configString ?: @"(空)"];
    
    if (!configString || configString.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB等级事件配置为空，保持当前配置"];
        return;
    }
    
    NSArray *events = [configString componentsSeparatedByString:@";"];
    NSMutableDictionary *levelEvents = [NSMutableDictionary dictionary];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 分割得到%lu个事件对", (unsigned long)events.count];
    
    for (NSString *event in events) {
        NSArray *parts = [event componentsSeparatedByString:@":"];
        if (parts.count == 2) {
            NSString *eventName = parts[0];
            double value = [parts[1] doubleValue];
            levelEvents[eventName] = @(value);
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 解析FB事件: %@ = %.2f", eventName, value];
        } else {
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB事件对格式错误，跳过: %@", event];
        }
    }
    
    self.fbLevelEventDict = levelEvents;
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB控制配置解析完成，共%lu个有效事件: %@", (unsigned long)levelEvents.count, self.fbLevelEventDict];
}

#pragma mark - 本地配置解析方法

- (BOOL)isFBSwitchEnabled {
    if (!self.fbControlConfig || self.fbControlConfig.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB控制配置为空，默认关闭切源开关"];
        return NO;
    }
    
    NSArray *params = [self.fbControlConfig componentsSeparatedByString:@";"];
    if (params.count >= 1) {
        BOOL enabled = [params[0] integerValue] == 1;
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB切源开关状态: %@", enabled ? @"开启" : @"关闭"];
        return enabled;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB控制配置格式错误，默认关闭切源开关"];
    return NO;
}

- (NSInteger)getFBShowThreshold {
    if (!self.fbControlConfig || self.fbControlConfig.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB控制配置为空，使用默认展示阈值: 2"];
        return 2;
    }
    
    NSArray *params = [self.fbControlConfig componentsSeparatedByString:@";"];
    if (params.count >= 2) {
        NSInteger threshold = [params[1] integerValue];
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB展示阈值: %ld", (long)threshold];
        return threshold;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB控制配置格式错误，使用默认展示阈值: 2"];
    return 2;
}

- (CGFloat)getFBClickRateThreshold {
    if (!self.fbControlConfig || self.fbControlConfig.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB控制配置为空，使用默认点击率阈值: 1.0"];
        return 1.0;
    }
    
    NSArray *params = [self.fbControlConfig componentsSeparatedByString:@";"];
    if (params.count >= 3) {
        CGFloat threshold = [params[2] floatValue] / 100.0; // 转换为小数形式
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB点击率阈值: %.2f%%", threshold * 100];
        return threshold;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB控制配置格式错误，使用默认点击率阈值: 1.0"];
    return 1.0;
}

- (NSString *)getAdjustEventTokenForLevel:(NSInteger)level {
    if (!self.adjustEventDict || self.adjustEventDict.count == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Adjust事件配置为空，关卡%ld无对应Token", (long)level];
        return nil;
    }
    
    NSString *eventKey = [NSString stringWithFormat:@"level_win_%ld", (long)level];
    NSString *token = self.adjustEventDict[eventKey];
    
    if (token && token.length > 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 找到关卡%ld的Adjust事件Token: %@", (long)level, token];
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 未找到关卡%ld的Adjust事件Token", (long)level];
    }
    
    return token;
}

- (NSString *)getAdjustPurchaseEventTokenForProduct:(NSString *)productId {
    if (!self.adjustEventDict || self.adjustEventDict.count == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Adjust事件配置为空，商品%@无对应Token", productId];
        return nil;
    }
    
    // 查找购买相关的事件Token
    NSString *purchaseKey = [NSString stringWithFormat:@"purchase_%@", productId ?: @"no_ads"];
    NSString *token = self.adjustEventDict[purchaseKey];
    
    if (!token) {
        // 如果没找到具体商品的Token，尝试查找通用购买Token
        token = self.adjustEventDict[@"purchase_no_ads"];
    }
    
    if (token && token.length > 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 找到商品%@的Adjust购买事件Token: %@", productId, token];
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 未找到商品%@的Adjust购买事件Token", productId];
    }
    
    return token;
}

- (void)parseAdjustEventConfig:(NSString *)configString {
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 开始解析Adjust事件配置: %@", configString ?: @"(空)"];
    
    if (!configString || configString.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Adjust事件配置为空，保持当前配置"];
        return;
    }
    
    NSArray *events = [configString componentsSeparatedByString:@";"];
    NSMutableDictionary *adjustEvents = [NSMutableDictionary dictionary];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 分割得到%lu个事件对", (unsigned long)events.count];
    
    for (NSString *event in events) {
        NSArray *parts = [event componentsSeparatedByString:@":"];
        if (parts.count == 2) {
            NSString *eventKey = parts[0];
            NSString *token = parts[1];
            adjustEvents[eventKey] = token;
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 解析Adjust事件: %@ = %@", eventKey, token];
        } else {
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Adjust事件对格式错误，跳过: %@", event];
        }
    }
    
    self.adjustEventDict = adjustEvents;
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Adjust事件配置解析完成，共%lu个有效事件: %@", (unsigned long)adjustEvents.count, self.adjustEventDict];
}

#pragma mark - 广告源切换控制

- (void)controlFBAdDisplay {
    // FB广告展示控制逻辑
    BOOL fbSwitchEnabled = [self isFBSwitchEnabled];
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] controlFBAdDisplay开始 - FB切源开关: %d", fbSwitchEnabled];
    
    if (!fbSwitchEnabled) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB切源功能未启用，跳过控制逻辑"];
        return;
    }
    
    // 检查展示次数和点击率阈值
    NSInteger showThreshold = [self getFBShowThreshold];
    CGFloat clickRateThreshold = [self getFBClickRateThreshold];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] BMS配置参数 - 展示阈值: %ld, 点击率阈值: %.2f%%",
          (long)showThreshold, clickRateThreshold * 100];
    
    // 获取当前FB广告统计数据（直接从NSUserDefaults获取，避免重复调用checkAndResetDailyStats）
    NSInteger todayShows = [[NSUserDefaults standardUserDefaults] integerForKey:KEY_FB_SHOW_COUNT_TODAY];
    NSInteger todayClicks = [[NSUserDefaults standardUserDefaults] integerForKey:KEY_FB_CLICK_COUNT_TODAY];
    
    // 计算当前点击率（不乘以100，保持小数形式）
    CGFloat currentClickRate = todayShows > 0 ? (CGFloat)todayClicks / todayShows : 0.0;
    CGFloat todayRevenue = 0.0; // 暂时设为0，如需要可以添加收入统计
    
    // 判断是否需要切换广告源
    BOOL shouldSwitchAdSource = NO;
    NSString *switchReason = @"";
    
    if (todayShows >= showThreshold) {
        if (currentClickRate < clickRateThreshold) {
            shouldSwitchAdSource = YES;
            switchReason = [NSString stringWithFormat:@"点击率过低 (%.2f%% < %.2f%%)", currentClickRate * 100, clickRateThreshold * 100];
        }
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB广告控制统计 - 今日展示: %ld/%ld, 点击: %ld, 点击率: %.2f%% (阈值: %.2f%%), 收入: $%.2f",
          (long)todayShows, (long)showThreshold, (long)todayClicks, currentClickRate * 100, clickRateThreshold * 100, todayRevenue];
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 切源判断条件 - 展示次数达标: %@, 点击率低于阈值: %@",
          todayShows >= showThreshold ? @"是" : @"否",
          currentClickRate < clickRateThreshold ? @"是" : @"否"];
    
    if (shouldSwitchAdSource) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 建议切换广告源: %@", switchReason];
        [self switchToOptimalAdSource];
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 当前广告源表现良好，无需切换"];
    }
}

- (void)switchToOptimalAdSource {
    // 切换到最优广告源的逻辑
    NSString *currentAdSource = [self getCurrentAdSource];
    NSString *optimalAdSource = [self selectOptimalAdSource];
    
    if (![currentAdSource isEqualToString:optimalAdSource]) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 切换广告源: %@ -> %@", currentAdSource, optimalAdSource];
        [self setCurrentAdSource:optimalAdSource];
        
        // 通知广告源切换
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WDAdSourceSwitched"
                                                            object:nil
                                                          userInfo:@{
                                                              @"from": currentAdSource,
                                                              @"to": optimalAdSource,
                                                              @"timestamp": @([[NSDate date] timeIntervalSince1970])
                                                          }];
    }
}

- (NSString *)selectOptimalAdSource {
    // 选择最优广告位逻辑 - 双广告位机制
    NSArray *availableSources = @[@"primary", @"secondary", @"backup"];
    NSString *currentSource = [self getCurrentAdSource];
    
    // 获取各广告源的历史表现数据
    NSDictionary *sourcePerformance = [self getAdSourcePerformanceData];
    
    // 计算各广告源的综合评分
    NSMutableDictionary *sourceScores = [NSMutableDictionary dictionary];
    
    for (NSString *source in availableSources) {
        if ([source isEqualToString:currentSource]) {
            continue; // 跳过当前广告源
        }
        
        NSDictionary *performance = sourcePerformance[source];
        CGFloat revenue = [performance[@"revenue"] floatValue];
        CGFloat clickRate = [performance[@"clickRate"] floatValue];
        NSInteger shows = [performance[@"shows"] integerValue];
        
        // 综合评分算法：收入权重50%，点击率权重30%，展示次数权重20%
        CGFloat score = (revenue * 0.5) + (clickRate * 100 * 0.3) + (shows * 0.0002);
        sourceScores[source] = @(score);
        
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 广告源 %@ 评分: %.2f (收入: $%.2f, 点击率: %.2f%%, 展示: %ld)",
              source, score, revenue, clickRate * 100, (long)shows];
    }
    
    // 选择评分最高的广告源
    NSString *optimalSource = currentSource;
    CGFloat maxScore = 0.0;
    
    for (NSString *source in sourceScores.allKeys) {
        CGFloat score = [sourceScores[source] floatValue];
        if (score > maxScore) {
            maxScore = score;
            optimalSource = source;
        }
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 选择最优广告源: %@ (评分: %.2f)", optimalSource, maxScore];
    return optimalSource;
}

- (NSDictionary *)getAdSourcePerformanceData {
    // 获取各广告源的历史表现数据
    NSMutableDictionary *performanceData = [NSMutableDictionary dictionary];
    NSArray *sources = @[@"primary", @"secondary", @"backup"];
    
    for (NSString *source in sources) {
        NSString *key = [NSString stringWithFormat:@"WD_AdSource_Performance_%@", source];
        NSDictionary *data = [[NSUserDefaults standardUserDefaults] objectForKey:key];
        
        if (data) {
            performanceData[source] = data;
        } else {
            // 默认数据
            performanceData[source] = @{
                @"revenue": @(0.0),
                @"clickRate": @(0.0),
                @"shows": @(0),
                @"clicks": @(0)
            };
        }
    }
    
    return [performanceData copy];
}

- (void)updateAdSourcePerformance:(NSString *)adSource revenue:(CGFloat)revenue shows:(NSInteger)shows clicks:(NSInteger)clicks {
    // 更新广告源表现数据
    NSString *key = [NSString stringWithFormat:@"WD_AdSource_Performance_%@", adSource];
    NSDictionary *currentData = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    
    CGFloat totalRevenue = [currentData[@"revenue"] floatValue] + revenue;
    NSInteger totalShows = [currentData[@"shows"] integerValue] + shows;
    NSInteger totalClicks = [currentData[@"clicks"] integerValue] + clicks;
    CGFloat clickRate = totalShows > 0 ? (CGFloat)totalClicks / totalShows : 0.0;
    
    NSDictionary *updatedData = @{
        @"revenue": @(totalRevenue),
        @"clickRate": @(clickRate),
        @"shows": @(totalShows),
        @"clicks": @(totalClicks),
        @"lastUpdate": @([[NSDate date] timeIntervalSince1970])
    };
    
    [[NSUserDefaults standardUserDefaults] setObject:updatedData forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 更新广告源 %@ 表现数据: 收入 $%.2f, 点击率 %.2f%%, 展示 %ld",
          adSource, totalRevenue, clickRate * 100, (long)totalShows];
}

- (NSString *)getCurrentAdSource {
    // 获取当前广告源
    NSString *currentSource = [[NSUserDefaults standardUserDefaults] objectForKey:@"WD_Current_Ad_Source"];
    return currentSource ?: @"primary";
}

- (void)setCurrentAdSource:(NSString *)adSource {
    // 设置当前广告源
    [[NSUserDefaults standardUserDefaults] setObject:adSource forKey:@"WD_Current_Ad_Source"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (BOOL)shouldShowFacebookAd {
    // 直接从本地配置获取最新的配置
    BOOL fbSwitchEnabled = [self isFBSwitchEnabled];
    NSInteger fbShowThreshold = [self getFBShowThreshold];
    CGFloat fbClickRateThreshold = [self getFBClickRateThreshold];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] shouldShowFacebookAd检查开始 - FB切源开关: %d, 展示阈值: %ld, 点击率阈值: %.2f%%",
          fbSwitchEnabled, (long)fbShowThreshold, fbClickRateThreshold * 100];
    
    // 检查切源开关
    if (!fbSwitchEnabled) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB切源开关关闭，始终展示FB广告"];
        return YES; // 不切换，始终展示FB广告
    }
    
    // 获取今日统计数据
    NSInteger todayShows = [self getTodayFBShows];
    double clickRate = [self getTodayFBClickRate];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB广告统计数据 - 今日展示: %ld, 点击率: %.2f%%", (long)todayShows, clickRate];
    
    // 判断展示条件
    if (todayShows <= fbShowThreshold) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 展示次数未达阈值，允许展示FB广告"];
        return YES; // 展示次数未达到阈值，可以展示
    }
    
    if (todayShows > fbShowThreshold && clickRate < fbClickRateThreshold) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 展示次数超阈值且点击率低于阈值，正常展示FB广告"];
        return YES; // 展示次数超过阈值且点击率低于阈值，正常展示FB广告
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB广告被阻止 - 展示次数: %ld (阈值: %ld), 点击率: %.2f%% (阈值: %.2f%%)",
          (long)todayShows, (long)fbShowThreshold, clickRate, fbClickRateThreshold * 100];
    return NO; // 展示次数超过阈值且点击率大于等于阈值，切换其他广告源
}

- (NSString *)selectOptimalAdUnitIdForType:(NSString *)adType {
    if (!adType || adType.length == 0) {
        return nil;
    }
    
    // 获取该广告类型的配置
    NSDictionary *typeConfig = self.adUnitConfigs[adType];
    if (!typeConfig) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] No config found for ad type: %@", adType];
        return nil;
    }
    
    NSString *fbAdUnitId = typeConfig[@"facebook"];
    NSString *otherAdUnitId = typeConfig[@"other"];
    
    // 检查是否可以展示FB广告
    BOOL canShowFB = [self shouldShowFacebookAd];
    
    if (!canShowFB) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Selected other ad unit for type: %@", adType];
        return otherAdUnitId;
    }
    
    // 如果两个广告位都可用，比较ECPM（这里简化处理，实际需要获取真实ECPM）
    double fbECPM = [self getECPMForAdUnit:fbAdUnitId];
    double otherECPM = [self getECPMForAdUnit:otherAdUnitId];
    
    NSString *selectedAdUnit = fbECPM >= otherECPM ? fbAdUnitId : otherAdUnitId;
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Selected ad unit: %@ (FB ECPM:%.2f, Other ECPM:%.2f)", selectedAdUnit, fbECPM, otherECPM];
    
    return selectedAdUnit;
}

- (double)getECPMForAdUnit:(NSString *)adUnitId {
    // 这里应该从实际的广告管理器获取ECPM数据
    // 暂时返回模拟数据
    if ([adUnitId containsString:@"facebook"]) {
        return 2.5; // FB广告位ECPM
    } else {
        return 2.0; // 其他广告位ECPM
    }
}

#pragma mark - 统计数据管理

- (void)recordFacebookAdShow {
    [self checkAndResetDailyStats];
    
    NSInteger currentShows = [[NSUserDefaults standardUserDefaults] integerForKey:KEY_FB_SHOW_COUNT_TODAY];
    [[NSUserDefaults standardUserDefaults] setInteger:currentShows + 1 forKey:KEY_FB_SHOW_COUNT_TODAY];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB ad show recorded, total today: %ld", (long)(currentShows + 1)];
    
    // 每次FB广告展示后，检查是否需要进行广告源切换控制
    [self controlFBAdDisplay];
}

- (void)recordFacebookAdClick {
    [self checkAndResetDailyStats];
    
    NSInteger currentClicks = [[NSUserDefaults standardUserDefaults] integerForKey:KEY_FB_CLICK_COUNT_TODAY];
    [[NSUserDefaults standardUserDefaults] setInteger:currentClicks + 1 forKey:KEY_FB_CLICK_COUNT_TODAY];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB ad click recorded, total today: %ld", (long)(currentClicks + 1)];
    
    // 每次FB广告点击后，检查是否需要进行广告源切换控制
    [self controlFBAdDisplay];
}

- (NSInteger)getTodayFBShows {
    [self checkAndResetDailyStats];
    return [[NSUserDefaults standardUserDefaults] integerForKey:KEY_FB_SHOW_COUNT_TODAY];
}

- (double)getTodayFBClickRate {
    [self checkAndResetDailyStats];
    
    NSInteger shows = [[NSUserDefaults standardUserDefaults] integerForKey:KEY_FB_SHOW_COUNT_TODAY];
    NSInteger clicks = [[NSUserDefaults standardUserDefaults] integerForKey:KEY_FB_CLICK_COUNT_TODAY];
    
    if (shows == 0) {
        return 0.0;
    }
    
    return (double)clicks / shows * 100.0; // 返回百分比
}

- (void)checkAndResetDailyStats {
    NSString *today = [self getTodayDateString];
    NSString *lastDate = [[NSUserDefaults standardUserDefaults] stringForKey:KEY_LAST_STAT_DATE];
    
    if (![today isEqualToString:lastDate]) {
        // 新的一天，重置统计数据
        [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:KEY_FB_SHOW_COUNT_TODAY];
        [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:KEY_FB_CLICK_COUNT_TODAY];
        [[NSUserDefaults standardUserDefaults] setObject:today forKey:KEY_LAST_STAT_DATE];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Daily stats reset for date: %@", today];
    }
}

- (NSString *)getTodayDateString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    return [formatter stringFromDate:[NSDate date]];
}

- (NSString *)getCurrentUserId {
    // 获取当前用户ID，可以从用户系统或设备标识获取
    NSString *userId = [[NSUserDefaults standardUserDefaults] stringForKey:@"WD_USER_ID"];
    if (!userId) {
        // 如果没有用户ID，使用设备标识符
        userId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"WD_USER_ID"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    return userId;
}

#pragma mark - 双广告位性能统计与ECPM比较

- (void)recordAdLoadRequest:(NSString *)adUnitId adType:(NSString *)adType {
    if (!adUnitId || adUnitId.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Invalid adUnitId for load request record"];
        return;
    }
    
    NSString *key = [NSString stringWithFormat:@"WD_AdUnit_Performance_%@", adUnitId];
    NSDictionary *currentData = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    
    // 获取当前数据
    NSInteger totalRequests = [currentData[@"totalRequests"] integerValue];
    NSInteger totalShows = [currentData[@"totalShows"] integerValue];
    NSInteger successShows = [currentData[@"successShows"] integerValue];
    double totalRevenue = [currentData[@"totalRevenue"] doubleValue];
    double totalECPM = [currentData[@"totalECPM"] doubleValue];
    NSInteger ecpmCount = [currentData[@"ecpmCount"] integerValue];
    
    // 更新请求次数
    totalRequests += 1;
    
    // 重新计算填充率（基于请求次数）
    double fillRate = totalRequests > 0 ? (double)successShows / totalRequests : 0.0;
    double averageECPM = ecpmCount > 0 ? totalECPM / ecpmCount : 0.0;
    double averageRevenue = successShows > 0 ? totalRevenue / successShows : 0.0;
    
    // 保存更新后的数据
    NSDictionary *updatedData = @{
        @"adUnitId": adUnitId,
        @"adType": adType ?: @"unknown",
        @"totalRequests": @(totalRequests),
        @"totalShows": @(totalShows),
        @"successShows": @(successShows),
        @"totalRevenue": @(totalRevenue),
        @"totalECPM": @(totalECPM),
        @"ecpmCount": @(ecpmCount),
        @"averageECPM": @(averageECPM),
        @"fillRate": @(fillRate),
        @"averageRevenue": @(averageRevenue),
        @"lastUpdate": @([[NSDate date] timeIntervalSince1970])
    };
    
    [[NSUserDefaults standardUserDefaults] setObject:updatedData forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 记录广告位 %@ 加载请求，总请求数: %ld", adUnitId, (long)totalRequests];
}

- (void)updateAdUnitPerformance:(NSString *)adUnitId
                         adType:(NSString *)adType
                           ecpm:(double)ecpm
                        revenue:(double)revenue
                      isSuccess:(BOOL)isSuccess {
    if (!adUnitId || adUnitId.length == 0) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] Invalid adUnitId for performance update"];
        return;
    }
    
    NSString *key = [NSString stringWithFormat:@"WD_AdUnit_Performance_%@", adUnitId];
    NSDictionary *currentData = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    
    // 获取当前数据
    NSInteger totalRequests = [currentData[@"totalRequests"] integerValue];
    NSInteger totalShows = [currentData[@"totalShows"] integerValue];
    NSInteger successShows = [currentData[@"successShows"] integerValue];
    double totalRevenue = [currentData[@"totalRevenue"] doubleValue];
    double totalECPM = [currentData[@"totalECPM"] doubleValue];
    NSInteger ecpmCount = [currentData[@"ecpmCount"] integerValue];
    
    // 更新数据
    totalShows += 1;
    if (isSuccess) {
        successShows += 1;
        totalRevenue += revenue;
    }
    
    if (ecpm > 0) {
         totalECPM += ecpm;
         ecpmCount += 1;
     }
     
     // 计算平均值（基于请求次数计算填充率）
     double averageECPM = ecpmCount > 0 ? totalECPM / ecpmCount : 0.0;
    double fillRate = totalRequests > 0 ? (double)successShows / totalRequests : 0.0;
    double averageRevenue = successShows > 0 ? totalRevenue / successShows : 0.0;
    
    // 保存更新后的数据
    NSDictionary *updatedData = @{
        @"adUnitId": adUnitId,
        @"adType": adType ?: @"unknown",
        @"totalRequests": @(totalRequests),
        @"totalShows": @(totalShows),
        @"successShows": @(successShows),
        @"totalRevenue": @(totalRevenue),
        @"totalECPM": @(totalECPM),
        @"ecpmCount": @(ecpmCount),
        @"averageECPM": @(averageECPM),
        @"fillRate": @(fillRate),
        @"averageRevenue": @(averageRevenue),
        @"lastUpdate": @([[NSDate date] timeIntervalSince1970])
    };
    
    [[NSUserDefaults standardUserDefaults] setObject:updatedData forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 更新广告位 %@ 性能数据: ECPM %.4f, 填充率 %.2f%%, 平均收入 %.4f",
          adUnitId, averageECPM, fillRate * 100, averageRevenue];
}

- (NSDictionary *)getAdUnitPerformanceData:(NSString *)adUnitId {
    if (!adUnitId || adUnitId.length == 0) {
        return nil;
    }
    
    NSString *key = [NSString stringWithFormat:@"WD_AdUnit_Performance_%@", adUnitId];
    NSDictionary *data = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    
    if (!data) {
        // 返回默认数据
        return @{
            @"adUnitId": adUnitId,
            @"adType": @"unknown",
            @"totalRequests": @(0),
            @"totalShows": @(0),
            @"successShows": @(0),
            @"totalRevenue": @(0.0),
            @"averageECPM": @(0.0),
            @"fillRate": @(0.0),
            @"averageRevenue": @(0.0),
            @"lastUpdate": @(0)
        };
    }
    
    return data;
 }

- (NSString *)selectOptimalAdUnitBetween:(NSString *)primaryAdUnitId
                            andSecondary:(NSString *)secondaryAdUnitId
                             primaryECPM:(double)primaryECPM
                           secondaryECPM:(double)secondaryECPM {
    if (!primaryAdUnitId && !secondaryAdUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 两个广告位ID都为空"];
        return nil;
    }
    
    if (!primaryAdUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 主广告位ID为空，选择备用广告位"];
        return secondaryAdUnitId;
    }
    
    if (!secondaryAdUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 备用广告位ID为空，选择主广告位"];
        return primaryAdUnitId;
    }
    
    // 获取历史性能数据
    NSDictionary *primaryData = [self getAdUnitPerformanceData:primaryAdUnitId];
    NSDictionary *secondaryData = [self getAdUnitPerformanceData:secondaryAdUnitId];
    
    // 计算综合评分
    double primaryScore = [self calculateAdUnitScore:primaryData currentECPM:primaryECPM];
    double secondaryScore = [self calculateAdUnitScore:secondaryData currentECPM:secondaryECPM];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 广告位评分比较 - 主广告位: %.2f, 备用广告位: %.2f", primaryScore, secondaryScore];
    
    // 选择评分更高的广告位
    if (primaryScore >= secondaryScore) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 选择主广告位 (评分更高)"];
        return primaryAdUnitId;
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 选择备用广告位 (评分更高)"];
        return secondaryAdUnitId;
    }
}

- (double)calculateAdUnitScore:(NSDictionary *)performanceData currentECPM:(double)currentECPM {
    if (!performanceData) {
        return currentECPM; // 如果没有历史数据，仅使用当前ECPM
    }
    
    double averageECPM = [performanceData[@"averageECPM"] doubleValue];
    double fillRate = [performanceData[@"fillRate"] doubleValue];
    double averageRevenue = [performanceData[@"averageRevenue"] doubleValue];
    NSInteger totalShows = [performanceData[@"totalShows"] integerValue];
    
    // 综合评分算法：
    // 1. 当前ECPM权重40%
    // 2. 历史平均ECPM权重30%
    // 3. 填充率权重20%
    // 4. 平均收入权重10%
    // 5. 数据量加权（展示次数越多，历史数据权重越高）
    
    double dataWeight = MIN(1.0, totalShows / 100.0); // 100次展示后历史数据权重达到最大
    double currentWeight = 1.0 - dataWeight * 0.5; // 当前ECPM权重随历史数据增加而降低
    
    double score = (currentECPM * currentWeight * 0.4) +
                   (averageECPM * dataWeight * 0.3) +
                   (fillRate * 100 * 0.2) +
                   (averageRevenue * 10 * 0.1);
    
    return score;
}

- (BOOL)shouldSwitchAdSource:(NSString *)currentAdUnitId adType:(NSString *)adType {
    if (!currentAdUnitId || !adType) {
        return NO;
    }
    
    NSDictionary *performanceData = [self getAdUnitPerformanceData:currentAdUnitId];
    if (!performanceData) {
        return NO; // 没有性能数据，不建议切换
    }
    
    double fillRate = [performanceData[@"fillRate"] doubleValue];
    double averageECPM = [performanceData[@"averageECPM"] doubleValue];
    NSInteger totalShows = [performanceData[@"totalShows"] integerValue];
    
    // 切换条件：
    // 1. 填充率低于50%且展示次数超过20次
    // 2. 平均ECPM低于1.0且展示次数超过50次
    // 3. 连续失败次数过多
    
    BOOL shouldSwitch = NO;
    NSString *reason = @"";
    
    if (totalShows >= 20 && fillRate < 0.5) {
        shouldSwitch = YES;
        reason = [NSString stringWithFormat:@"填充率过低 (%.1f%%)", fillRate * 100];
    } else if (totalShows >= 50 && averageECPM < 1.0) {
        shouldSwitch = YES;
        reason = [NSString stringWithFormat:@"ECPM过低 (%.4f)", averageECPM];
    }
    
    if (shouldSwitch) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 建议切换广告源 %@: %@", currentAdUnitId, reason];
    }
    
    return shouldSwitch;
}

- (double)getAdUnitScore:(NSString *)adUnitId {
    if (!adUnitId) {
        return 0.0;
    }
    
    NSDictionary *performanceData = [self getAdUnitPerformanceData:adUnitId];
    return [self calculateAdUnitScore:performanceData currentECPM:0.0];
}

- (void)resetAdUnitPerformanceData:(NSString *)adUnitId {
    if (!adUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 重置性能数据失败：广告位ID为空"];
        return;
    }
    
    NSString *key = [NSString stringWithFormat:@"WD_AdUnit_Performance_%@", adUnitId];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 已重置广告位 %@ 的性能数据", adUnitId];
}

- (NSDictionary *)getPerformanceReport {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *allData = [defaults dictionaryRepresentation];
    NSMutableDictionary *report = [NSMutableDictionary dictionary];
    
    // 遍历所有存储的数据，找出广告位性能数据
    for (NSString *key in allData.allKeys) {
        if ([key hasPrefix:@"WD_AdUnit_Performance_"]) {
            NSString *adUnitId = [key substringFromIndex:[@"WD_AdUnit_Performance_" length]];
            NSDictionary *performanceData = [allData objectForKey:key];
            
            if (performanceData && [performanceData isKindOfClass:[NSDictionary class]]) {
                report[adUnitId] = performanceData;
            }
        }
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 生成性能报告，包含 %lu 个广告位的数据", (unsigned long)report.count];
    return [report copy];
}

- (NSString *)getCurrentSessionId {
    // 获取当前会话ID
    NSString *sessionId = [[NSUserDefaults standardUserDefaults] stringForKey:@"WD_SESSION_ID"];
    NSDate *sessionStartTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"WD_SESSION_START_TIME"];
    
    // 检查会话是否过期（30分钟）
    if (!sessionId || !sessionStartTime || [[NSDate date] timeIntervalSinceDate:sessionStartTime] > 1800) {
        sessionId = [[NSUUID UUID] UUIDString];
        [[NSUserDefaults standardUserDefaults] setObject:sessionId forKey:@"WD_SESSION_ID"];
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"WD_SESSION_START_TIME"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    return sessionId;
}

- (BOOL)shouldSwitchAdForType:(NSString *)adType adUnitId:(NSString *)adUnitId {
    if (!adType || !adUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] shouldSwitchAdForType: 参数无效"];
        return NO;
    }
    
    // 直接从本地配置获取最新的配置
    BOOL fbSwitchFlag = [self isFBSwitchEnabled];
    NSInteger fbShowThreshold = [self getFBShowThreshold];
    CGFloat fbClickRateThreshold = [self getFBClickRateThreshold];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 检查是否需要切换广告位 - 类型: %@, 广告位: %@", adType, adUnitId];
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 当前BMS配置 - FB切源开关: %d, 展示阈值: %ld, 点击率阈值: %.2f%%",
          fbSwitchFlag, (long)fbShowThreshold, fbClickRateThreshold * 100];
    
    // 1. 检查FB策略控制
    if ([adType isEqualToString:@"rewarded_video"] && fbSwitchFlag) {
        // 检查FB广告展示次数和点击率阈值
        NSInteger todayShows = [self getTodayFBShows];
        double todayClickRate = [self getTodayFBClickRate];
        
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB策略检查 - 今日展示: %ld, 点击率: %.2f%%, 展示阈值: %ld, 点击率阈值: %.2f%%",
              (long)todayShows, todayClickRate, (long)fbShowThreshold, fbClickRateThreshold * 100];
        
        // 根据FB切源逻辑判断是否需要切换
        // 条件：展示次数<=阈值 OR (展示次数>阈值 AND 点击率<阈值) 时展示FB广告，其他情况切换
        if (todayShows <= fbShowThreshold) {
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB策略: 展示次数未达阈值，无需切换"];
            return NO; // 展示次数未达阈值，无需切换
        }
        
        if (todayShows > fbShowThreshold && todayClickRate < fbClickRateThreshold) {
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB策略: 展示次数超阈值且点击率低于阈值，无需切换"];
            return NO; // 展示次数超阈值且点击率低于阈值，无需切换
        }
        
        // 展示次数超阈值且点击率大于等于阈值，建议切换
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB策略触发切换: 展示次数超阈值且点击率达标"];
        return YES;
    } else if ([adType isEqualToString:@"rewarded_video"]) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB策略已关闭，跳过FB切源检查"];
    }
    
    // 2. 检查广告位性能数据
    NSDictionary *performanceData = [self getAdUnitPerformanceData:adUnitId];
    if (performanceData) {
        double fillRate = [performanceData[@"fillRate"] doubleValue];
        double averageECPM = [performanceData[@"averageECPM"] doubleValue];
        NSInteger totalShows = [performanceData[@"totalShows"] integerValue];
        
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 广告位性能检查 - 填充率: %.2f%%, 平均ECPM: %.4f, 总展示: %ld",
              fillRate * 100, averageECPM, (long)totalShows];
        
        // 性能切换条件
        if (totalShows >= 10) { // 至少有10次展示数据
            if (fillRate < 0.3) { // 填充率低于30%
                [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 性能策略触发切换: 填充率过低 (%.1f%%)", fillRate * 100];
                return YES;
            }
            if (averageECPM < 0.5 && totalShows >= 20) { // ECPM过低且有足够数据
                [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 性能策略触发切换: ECPM过低 (%.4f)", averageECPM];
                return YES;
            }
        }
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 无需切换广告位"];
    return NO;
}

- (BOOL)shouldShowAd:(NSString *)adUnitId adType:(NSString *)adType {
    if (!adUnitId || !adType) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] shouldShowAd: 参数无效"];
        return YES; // 参数无效时默认允许展示
    }
    
    // 直接从本地配置获取最新的配置
    BOOL fbSwitchFlag = [self isFBSwitchEnabled];
    NSInteger fbShowThreshold = [self getFBShowThreshold];
    CGFloat fbClickRateThreshold = [self getFBClickRateThreshold];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 检查广告位是否应该展示 - 类型: %@, 广告位: %@", adType, adUnitId];
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 当前BMS配置 - FB切源开关: %d, 展示阈值: %ld, 点击率阈值: %.2f%%",
          fbSwitchFlag, (long)fbShowThreshold, fbClickRateThreshold];
    
    // 检查FB策略控制
    if ([adType isEqualToString:@"rewarded_video"] && fbSwitchFlag) {
        // 检查FB广告展示次数和点击率阈值
        NSInteger todayShows = [self getTodayFBShows];
        double todayClickRate = [self getTodayFBClickRate];
        
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB策略检查 - 今日展示: %ld, 点击率: %.2f%%, 展示阈值: %ld, 点击率阈值: %.2f%%",
              (long)todayShows, todayClickRate, (long)fbShowThreshold, fbClickRateThreshold];
        
        // 根据FB切源逻辑判断是否允许展示
        // 条件：展示次数<=阈值 OR (展示次数>阈值 AND 点击率<阈值) 时展示FB广告，其他情况切换
        if (todayShows <= fbShowThreshold) {
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB策略: 展示次数未达阈值，允许展示"];
            return YES; // 展示次数未达阈值，允许展示
        }
        
        if (todayShows > fbShowThreshold && todayClickRate < fbClickRateThreshold) {
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB策略: 展示次数超阈值且点击率低于阈值，允许展示"];
            return YES; // 展示次数超阈值且点击率低于阈值，允许展示
        }
        
        // 展示次数超阈值且点击率大于等于阈值，不允许展示（切换其他广告源）
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB策略阻止展示: 展示次数超阈值且点击率达标，切换其他广告源"];
        return NO;
    } else if ([adType isEqualToString:@"rewarded_video"]) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] FB策略已关闭，跳过FB展示控制检查"];
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 广告位允许展示"];
    return YES;
}

- (BOOL)shouldShowAdWithAdUnitId:(NSString *)adUnitId adType:(NSString *)adType {
    // 兼容方法，直接调用shouldShowAd
    return [self shouldShowAd:adUnitId adType:adType];
}

- (BOOL)shouldShowAd:(NSString *)adUnitId adType:(NSString *)adType isSecondaryAdUnit:(BOOL)isSecondaryAdUnit {
    if (!adUnitId || !adType) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] shouldShowAd:isSecondaryAdUnit: 参数无效"];
        return YES; // 参数无效时默认允许展示
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 检查广告位是否应该展示 - 类型: %@, 广告位: %@, 是否备用广告位: %@",
          adType, adUnitId, isSecondaryAdUnit ? @"是" : @"否"];
    
    // 获取广告位的网络信息
    NSString *adNetwork = [self getAdNetworkInfo:adUnitId];
    BOOL isFacebookAd = NO;
    
    if (adNetwork) {
        // 判断是否为Facebook广告网络
        isFacebookAd = [adNetwork.lowercaseString containsString:@"facebook"] ||
                       [adNetwork.lowercaseString containsString:@"meta"] ||
                       [adNetwork.lowercaseString containsString:@"fb"];
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 根据记录的网络信息判断 - 网络: %@, 是否Facebook: %@", adNetwork, isFacebookAd ? @"是" : @"否"];
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 未找到广告位网络信息记录: %@", adUnitId];
        
        // 对于备用广告位，如果没有网络信息记录，则默认允许展示
        if (isSecondaryAdUnit) {
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 备用广告位无网络信息记录，默认允许展示"];
            return YES;
        }
    }
    
    // 对于备用广告位，只需要判断是否为Facebook网络
    if (isSecondaryAdUnit) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 备用广告位简化判断 - 是否Facebook广告: %@", isFacebookAd ? @"是" : @"否"];
        
        if (isFacebookAd) {
            // 如果是Facebook广告，检查FB切源开关
            BOOL fbSwitchFlag = [self isFBSwitchEnabled];
            if ([adType isEqualToString:@"rewarded_video"] && fbSwitchFlag) {
                [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 备用广告位FB策略: FB切源开关已开启，不允许展示Facebook广告"];
                return NO;
            } else {
                [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 备用广告位FB策略: FB切源开关已关闭或非激励视频，允许展示"];
                return YES;
            }
        } else {
            [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 备用广告位: 非Facebook广告，允许展示"];
            return YES;
        }
    }
    
    // 对于主广告位，如果是Facebook广告，使用完整的FB策略控制逻辑
    if (isFacebookAd) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 主广告位Facebook广告，使用完整FB策略控制逻辑"];
        return [self shouldShowAd:adUnitId adType:adType];
    } else {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 主广告位非Facebook广告，允许展示"];
        return YES;
    }
}



- (NSString *)getTodayDateKey {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    return [formatter stringFromDate:[NSDate date]];
}

- (void)recordAdUnitPerformance:(NSString *)adUnitId
                           ecpm:(double)ecpm
                       fillRate:(double)fillRate
                      clickRate:(double)clickRate
                      isSuccess:(BOOL)isSuccess {
    if (!adUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] recordAdUnitPerformance: 广告位ID为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 记录广告位性能 - ID: %@, ECPM: %.4f, 填充率: %.2f%%, 点击率: %.2f%%, 成功: %@",
          adUnitId, ecpm, fillRate * 100, clickRate * 100, isSuccess ? @"是" : @"否"];
    
    NSString *key = [NSString stringWithFormat:@"WD_AdUnit_Performance_%@", adUnitId];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *performanceData = [[defaults dictionaryForKey:key] mutableCopy];
    
    if (!performanceData) {
        performanceData = [NSMutableDictionary dictionary];
        performanceData[@"totalRequests"] = @0;
        performanceData[@"totalShows"] = @0;
        performanceData[@"totalClicks"] = @0;
        performanceData[@"totalRevenue"] = @0.0;
        performanceData[@"averageECPM"] = @0.0;
        performanceData[@"fillRate"] = @0.0;
        performanceData[@"clickRate"] = @0.0;
        performanceData[@"averageRevenue"] = @0.0;
        performanceData[@"lastUpdated"] = [NSDate date];
    }
    
    // 更新统计数据
    NSInteger totalRequests = [performanceData[@"totalRequests"] integerValue] + 1;
    NSInteger totalShows = [performanceData[@"totalShows"] integerValue];
    NSInteger totalClicks = [performanceData[@"totalClicks"] integerValue];
    double totalRevenue = [performanceData[@"totalRevenue"] doubleValue];
    
    if (isSuccess) {
        totalShows += 1;
        totalRevenue += ecpm;
        
        // 如果有点击率数据，更新点击次数
        if (clickRate > 0) {
            totalClicks += (NSInteger)(clickRate * totalShows);
        }
    }
    
    // 计算平均值
    double averageECPM = totalShows > 0 ? totalRevenue / totalShows : 0.0;
    double calculatedFillRate = totalRequests > 0 ? (double)totalShows / totalRequests : 0.0;
    double calculatedClickRate = totalShows > 0 ? (double)totalClicks / totalShows : 0.0;
    double averageRevenue = totalShows > 0 ? totalRevenue / totalShows : 0.0;
    
    // 更新数据
    performanceData[@"totalRequests"] = @(totalRequests);
    performanceData[@"totalShows"] = @(totalShows);
    performanceData[@"totalClicks"] = @(totalClicks);
    performanceData[@"totalRevenue"] = @(totalRevenue);
    performanceData[@"averageECPM"] = @(averageECPM);
    performanceData[@"fillRate"] = @(calculatedFillRate);
    performanceData[@"clickRate"] = @(calculatedClickRate);
    performanceData[@"averageRevenue"] = @(averageRevenue);
    performanceData[@"lastUpdated"] = [NSDate date];
    
    [defaults setObject:performanceData forKey:key];
    [defaults synchronize];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 性能数据已更新 - 总请求: %ld, 总展示: %ld, 平均ECPM: %.4f, 填充率: %.2f%%",
          (long)totalRequests, (long)totalShows, averageECPM, calculatedFillRate * 100];
}

- (NSString *)compareAdUnitsAndSelectOptimal:(NSString *)primaryAdUnitId
                            secondaryAdUnitId:(NSString *)secondaryAdUnitId {
    if (!primaryAdUnitId && !secondaryAdUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] compareAdUnitsAndSelectOptimal: 两个广告位ID都为空"];
        return nil;
    }
    
    if (!primaryAdUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 主广告位ID为空，选择备用广告位: %@", secondaryAdUnitId];
        return secondaryAdUnitId;
    }
    
    if (!secondaryAdUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 备用广告位ID为空，选择主广告位: %@", primaryAdUnitId];
        return primaryAdUnitId;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 比较广告位性能 - 主: %@, 备用: %@", primaryAdUnitId, secondaryAdUnitId];
    
    // 获取两个广告位的性能数据
    NSDictionary *primaryData = [self getAdUnitPerformanceData:primaryAdUnitId];
    NSDictionary *secondaryData = [self getAdUnitPerformanceData:secondaryAdUnitId];
    
    // 计算综合评分
    double primaryScore = [self calculateAdUnitScore:primaryData currentECPM:0.0];
    double secondaryScore = [self calculateAdUnitScore:secondaryData currentECPM:0.0];
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 广告位评分 - 主广告位: %.2f, 备用广告位: %.2f", primaryScore, secondaryScore];
    
    // 选择评分更高的广告位
    NSString *selectedAdUnitId;
    if (primaryScore >= secondaryScore) {
        selectedAdUnitId = primaryAdUnitId;
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 选择主广告位 (评分: %.2f)", primaryScore];
    } else {
        selectedAdUnitId = secondaryAdUnitId;
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 选择备用广告位 (评分: %.2f)", secondaryScore];
    }
    
    return selectedAdUnitId;
}

#pragma mark - 广告网络信息管理

- (void)recordAdNetworkInfo:(NSString *)adNetwork adUnitId:(NSString *)adUnitId {
    if (!adNetwork || !adUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] recordAdNetworkInfo: 参数无效 - adNetwork: %@, adUnitId: %@", adNetwork, adUnitId];
        return;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 记录广告网络信息 - 广告位: %@, 网络: %@", adUnitId, adNetwork];
    
    @synchronized(self.adNetworkInfoDict) {
        [self.adNetworkInfoDict setObject:adNetwork forKey:adUnitId];
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 广告网络信息已记录 - 当前存储数量: %lu", (unsigned long)self.adNetworkInfoDict.count];
}

- (NSString *)getAdNetworkInfo:(NSString *)adUnitId {
    if (!adUnitId) {
        [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] getAdNetworkInfo: 广告位ID为空"];
        return nil;
    }
    
    NSString *adNetwork = nil;
    @synchronized(self.adNetworkInfoDict) {
        adNetwork = [self.adNetworkInfoDict objectForKey:adUnitId];
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"🏷️ [Commercial] 获取广告网络信息 - 广告位: %@, 网络: %@", adUnitId, adNetwork ?: @"未记录"];
    
    return adNetwork;
}

@end
